package com.example.yichuangyun.ui.activity.follow;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;

import com.bumptech.glide.Glide;
import com.example.yichuangyun.R;
import com.example.yichuangyun.config.Constant;
import com.example.yichuangyun.databinding.ActivityAddFollowBinding;
import com.example.yichuangyun.dialog.SinglePickerView;
import com.example.yichuangyun.dialog.TimePicker;
import com.example.yichuangyun.http.ApiFactory;
import com.example.yichuangyun.http.HttpRespond;
import com.example.yichuangyun.http.MyObserver;
import com.example.yichuangyun.http.RetrofitHelper;
import com.example.yichuangyun.model.EventBusModel;
import com.example.yichuangyun.model.business.LabelModel;
import com.example.yichuangyun.mvvm.base.BaseActivity;
import com.example.yichuangyun.mvvm.base.BaseViewModel;
import com.example.yichuangyun.utils.CommonUtil;
import com.example.yichuangyun.utils.TimeUtils;
import com.example.yichuangyun.utils.ToastHelper;
import com.example.yichuangyun.utils.pictrue.GlideEngine;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.config.SelectModeConfig;
import com.luck.picture.lib.engine.CompressFileEngine;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.style.PictureSelectorStyle;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import top.zibin.luban.Luban;
import top.zibin.luban.OnNewCompressListener;

/**
 * 添加跟进
 */
public class AddFollowActivity extends BaseActivity<ActivityAddFollowBinding, BaseViewModel> implements View.OnClickListener {

    private ActivityResultLauncher<Intent> launcherResult;
    private final List<String> followTypeData = new ArrayList<>();
    private final List<LabelModel> followTypeLabelData = new ArrayList<>();
    /**
     * 跟进方式：1-云来电、2-云去电、3-未接、4-微信、5-面访、6-其他
     */
    private int followType;
    private List<String> mTelList = new ArrayList<>();
    private String id;
    /**
     * 0商机、1联系人
     */
    private int flag;
    private String signUrl;

    @Override
    protected BaseViewModel bindModel() {
        return getViewModel(this, BaseViewModel.class);
    }

    @Override
    protected void initInject() {
        getActivityComponent().inject(this);
    }

    @Override
    public void initData() {
        launcherResult = createActivityResultLauncher();
        initTitleBar(getString(R.string.add_follow));
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            flag = bundle.getInt(Constant.flagKey, 0);
            if (bundle.getString(Constant.nameKey) != null) {
                binding.etName.setText(bundle.getString(Constant.nameKey));
            }
            if (bundle.getString(Constant.phoneKey) != null) {
                binding.tvPhone.setText(bundle.getString(Constant.phoneKey));
            }
            if (bundle.getSerializable(Constant.telKey) != null) {
                mTelList = bundle.getStringArrayList(Constant.telKey);
                if (mTelList != null && mTelList.size() > 0) {
                    binding.tvPhone.setText(mTelList.get(0));
                }
            }
            if (bundle.getString(Constant.businessIdKey) != null) {
                id = bundle.getString(Constant.businessIdKey);
            }
        }
        binding.tvFollowTime.setText(TimeUtils.getCurTime());
        getFollowType();
    }

    /**
     * @param flag 0联系人电话、1跟进方式
     */
    private void initSimplePickerView(int flag, List<String> data, String title) {
        SinglePickerView singlePickerView = new SinglePickerView(this, title, data) {
            @Override
            public void confirm(String label, int position) {
                if (flag == 0) {
                    binding.tvPhone.setText(label);
                } else {
                    binding.tvFollowType.setText(label);
                    followType = Integer.parseInt(followTypeLabelData.get(position).getCode());
                    if (followType == 5) {
                        binding.llFaceAddress.setVisibility(View.VISIBLE);
                        binding.llSignImg.setVisibility(View.VISIBLE);
                    } else {
                        binding.llFaceAddress.setVisibility(View.GONE);
                        binding.llSignImg.setVisibility(View.GONE);
                    }
                }
                changeBtnStatus();
            }
        };
        singlePickerView.showSinglePickerView();
    }

    /**
     * 跟进方式
     */
    private void getFollowType() {
        RetrofitHelper.getInstance().execute(RetrofitHelper.getService().getLabel(Constant.followType), new MyObserver<HttpRespond<List<LabelModel>>>() {
            @Override
            protected void onSuccess(HttpRespond<List<LabelModel>> listHttpRespond) {
                if (Constant.SUCCESS == listHttpRespond.code) {
                    if (listHttpRespond.data != null && listHttpRespond.data.size() > 0) {
                        for (LabelModel labelModel : listHttpRespond.data) {
                            if (!labelModel.getRemark().contains("400") && !labelModel.getRemark().equals(getString(R.string.business_group))) {
                                followTypeLabelData.add(labelModel);
                                followTypeData.add(labelModel.getRemark());
                            }
                        }
                    }
                }
            }
        });
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    protected void initClick() {
        binding.etName.setOnTextChangeListener(text -> changeBtnStatus());
        binding.etNote.setOnTextChangeListener(text -> {
            binding.tvTextCount.setText(getString(R.string.text_count, text.toString().trim().length()));
            changeBtnStatus();
        });

        binding.etNote.setOnTouchListener((v, event) -> {
            // 解决scrollView中嵌套EditText导致不能上下滑动的问题
            v.getParent().requestDisallowInterceptTouchEvent(true);
            if (event.getAction() == MotionEvent.ACTION_UP) {
                v.getParent().requestDisallowInterceptTouchEvent(false);
            }
            return false;
        });

        binding.etFaceLocation.setOnTextChangeListener(text -> changeBtnStatus());
        binding.rlPhone.setOnClickListener(this);
        binding.rlFollowType.setOnClickListener(this);
        binding.rlFollowNextTime.setOnClickListener(this);
        binding.ivSign.setOnClickListener(this);
        binding.btnConfirm.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        CommonUtil.closeKeyboard(this);
        if (!CommonUtil.isCanClick()) {
            return;
        }
        int vId = v.getId();
        if (vId == R.id.rl_phone) {
            if (mTelList.size() > 1) {
                initSimplePickerView(0, mTelList, getString(R.string.contact_way));
            }
            changeBtnStatus();
        } else if (vId == R.id.rl_follow_type) {
            initSimplePickerView(1, followTypeData, getString(R.string.follow_type));
        } else if (vId == R.id.rl_follow_next_time) {
            initTimePickerView();
        } else if (vId == R.id.iv_sign) {
            PictureSelector.create(context).openGallery(SelectMimeType.ofImage())// 全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                    .setImageEngine(GlideEngine.createGlideEngine())// 外部传入图片加载引擎，必传项
                    .setSelectorUIStyle(new PictureSelectorStyle())
                    .setCameraImageFormat(PictureMimeType.PNG) // 拍照保存图片格式后缀,默认jpeg,Android Q使用PictureMimeType.PNG_Q
                    .setSelectionMode(SelectModeConfig.SINGLE) // 单选
                    .setCompressEngine((CompressFileEngine) (context, source, call) -> Luban.with(context).load(source).ignoreBy(100)
                            .setCompressListener(new OnNewCompressListener() {
                                @Override
                                public void onStart() {
                                }

                                @Override
                                public void onSuccess(String source, File compressFile) {
                                    if (call != null) {
                                        call.onCallback(source, compressFile.getAbsolutePath());
                                    }
                                }

                                @Override
                                public void onError(String source, Throwable e) {
                                    if (call != null) {
                                        call.onCallback(source, null);
                                    }
                                }
                            }).launch())
                    .forResult(launcherResult);
        } else if (vId == R.id.btn_confirm) {
            save();
        }
    }

    /**
     * 添加跟进/修改跟进
     */
    private void save() {
        JSONObject requestDate = new JSONObject();
        try {
            requestDate.put(flag == 0 ? "chanceId" : "contactId", id);
            requestDate.put("followName", binding.etName.getText().toString().trim());
            requestDate.put("followTel", binding.tvPhone.getText().toString());
            requestDate.put("followType", followType);
            requestDate.put("followRemark", binding.etNote.getText().toString().trim());
            requestDate.put("followTime", binding.tvFollowTime.getText().toString());
            requestDate.put("nextFollowTime", binding.tvFollowNextTime.getText().toString() + (flag == 0 ? "" : " 00:00:00"));
            if (followType == 5) {
                requestDate.put("viewAddress", binding.etFaceLocation.getText().toString().trim());
                requestDate.put("viewFile", signUrl);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), requestDate.toString());
        RetrofitHelper.getInstance().execute(flag == 0
                ? RetrofitHelper.getService().addFollowUp(requestBody)
                : RetrofitHelper.getService().addContactsFollowUp(requestBody), new MyObserver<HttpRespond<String>>() {
            @Override
            protected void onSuccess(HttpRespond<String> stringHttpRespond) {
                if (Constant.SUCCESS == stringHttpRespond.code) {
                    ToastHelper.show(getString(R.string.add_follow_success));
                    EventBus.getDefault().post(new EventBusModel(Constant.refreshFollowList));
                    EventBus.getDefault().post(new EventBusModel(flag == 0 ? Constant.refreshInformationDetail : Constant.refreshContactDetailsData));
                    finish();
                } else {
                    ToastHelper.show(stringHttpRespond.msg);
                }
            }
        });
    }

    /**
     * 时间弹窗
     */
    private void initTimePickerView() {
        Calendar startDate = Calendar.getInstance();
        Calendar endDate = Calendar.getInstance();
        endDate.add(Calendar.DATE, 30);
        TimePicker timePicker = new TimePicker(this, startDate, endDate) {
            @Override
            public void confirm(String date) {
                binding.tvFollowNextTime.setText(date);
                changeBtnStatus();
            }
        };
        timePicker.showPickerView();
    }

    private void changeBtnStatus() {
        if (!TextUtils.isEmpty(binding.etName.getText().toString().trim()) && !TextUtils.isEmpty(binding.tvPhone.getText().toString())
                && !TextUtils.isEmpty(binding.tvFollowType.getText())
                && !TextUtils.isEmpty(binding.tvFollowNextTime.getText())
                && !TextUtils.isEmpty(binding.etNote.getText().toString().trim())
        ) {
            if (followType == 5) {
                if (!TextUtils.isEmpty(binding.etFaceLocation.getText().toString().trim())
                        && !TextUtils.isEmpty(signUrl)) {
                    binding.btnConfirm.setEnabled(true);
                    binding.btnConfirm.setBackgroundResource(R.drawable.shape_button_sel);
                } else {
                    binding.btnConfirm.setEnabled(false);
                    binding.btnConfirm.setBackgroundResource(R.drawable.shape_button_def);
                }
            } else {
                binding.btnConfirm.setEnabled(true);
                binding.btnConfirm.setBackgroundResource(R.drawable.shape_button_sel);
            }
        } else {
            binding.btnConfirm.setEnabled(false);
            binding.btnConfirm.setBackgroundResource(R.drawable.shape_button_def);
        }
    }

    /**
     * 上传图片
     */
    private void uploadImg(File file) {
        showLoadingDialog();
        MultipartBody.Part part = null;
        RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        try {
            // 路径有中文名要进行编码
            part = MultipartBody.Part.createFormData("file", URLEncoder.encode(file.getName(), "utf-8"), requestBody);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        RetrofitHelper.getInstance().execute(RetrofitHelper.getService().uploadImage(part), new MyObserver<HttpRespond<String>>() {
            @Override
            protected void onSuccess(HttpRespond<String> stringHttpRespond) {
                if (Constant.SUCCESS == stringHttpRespond.code) {
                    if (!TextUtils.isEmpty(stringHttpRespond.data)) {
                        signUrl = stringHttpRespond.data;
                        Glide.with(context).load(ApiFactory.IMAGE_UPLOAD + signUrl).into(binding.ivSign);
                        changeBtnStatus();
                    } else {
                        ToastHelper.show(stringHttpRespond.msg);
                    }
                }
                dismissLoadingDialog();
            }

            @Override
            protected void onFail(Throwable e) {
                dismissLoadingDialog();
            }
        });
    }

    /**
     * 创建一个ActivityResultLauncher
     */
    private ActivityResultLauncher<Intent> createActivityResultLauncher() {
        return registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
            int resultCode = result.getResultCode();
            if (resultCode == RESULT_OK) {
                List<LocalMedia> selectList = PictureSelector.obtainSelectorList(result.getData());
                for (int i = 0; i < selectList.size(); i++) {
                    LocalMedia media = selectList.get(i);
                    File file = new File(media.getCompressPath() == null ? media.getRealPath() : media.getCompressPath());
                    uploadImg(file);
                }
            }
        });
    }
}